package org.flowable.app.cusTaskExe;

import cmbchina.util.*;
import cmbchina.util.db.FlowDb;
import cmbchina.util.db.FlowFormDb;
import cmbchina.util.http.DbServiceRequestUtil;
import org.apache.commons.lang3.StringUtils;
import org.flowable.app.model.runtime.CompleteFormRepresentation;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.service.delegate.DelegateTask;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by sevenlm on 2017/12/22.
 */
public class CusSendSmsTask implements CusTask {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CusSendSmsTask.class);
    @Override
    public AjaxJson exe( CompleteFormRepresentation completeTaskFormRepresentation, TaskService taskService, String taskId, String resultParmas, String processInstId,String taskDefinitionKey) {
       logger.info("==============sendSmsTask start=============");
        //将流程状态置为运行中
        FlowDb.updateFlowState(2, processInstId);
        AjaxJson ajaxJson =new AjaxJson();
        String sender = "";
        String sendMsg = "";
        if(completeTaskFormRepresentation.getValues().get("sender")==null ){
            ajaxJson.setSuccess(true);
            ajaxJson.setMsg("该任务步骤没有手机号码");
            logger.error("该任务步骤没有手机号码");
            FlowDb.updateFlowState(4, processInstId);

            //将任务节点改为失败
            FlowFormDb.updateFlowFormState(4,processInstId,taskDefinitionKey,"9527",ajaxJson.getMsg(),"");
            taskService.setVariableLocal(taskId, "result", ajaxJson.getMsg());
//            return  ajaxJson;
        }else if( completeTaskFormRepresentation.getValues().get("sendMsg")==null){
            ajaxJson.setMsg("该任务步骤没有短信内容");
            logger.error("该任务步骤没有短信内容");
            FlowDb.updateFlowState(4, processInstId);
        }

            sender = completeTaskFormRepresentation.getValues().get("sender")==null?"":completeTaskFormRepresentation.getValues().get("sender").toString();
            sendMsg = completeTaskFormRepresentation.getValues().get("sendMsg")==null?"":completeTaskFormRepresentation.getValues().get("sendMsg").toString();
//            sender = completeTaskFormRepresentation.getValues().get("sender").toString();
//            sendMsg = completeTaskFormRepresentation.getValues().get("sendMsg").toString();
            logger.info("sendMsg======================================================================" + sendMsg);
            Map<String,Object> mapScriptParams = new HashMap<String, Object>();
            String script = sender;

            //跟新缓存
            try {

                String sendExe = completeTaskFormRepresentation.getValues().get("sendExe")!=null?completeTaskFormRepresentation.getValues().get("sendExe").toString():"";
                logger.error("sendExe:"+sendExe);
                Map<String,String>  userMap = FlowDb.queryCreateUserId(processInstId);
                String createUserId = userMap.get("userId");
                taskService.setVariable(taskId, "userId", createUserId);
                taskService.setVariable(taskId, "userName", userMap.get("userName"));
                String exeUserPhone = "";
                if(taskService.getVariable(taskId,"exeUserPhone")!=null && !"".equals(taskService.getVariable(taskId,"exeUserPhone").toString())){
                    exeUserPhone = taskService.getVariable(taskId,"exeUserPhone").toString();
                    userMap.put("exeUserPhone",exeUserPhone);
                }
                //配置了给执行人发，就需要处理执行人信息
                if("是".equals(sendExe)){

//                Map<String,String>  userMap = FlowDb.queryCreateUserId(processInstId);
//                String createUserId = userMap.get("userId");
//                taskService.setVariable(taskId, "userId", createUserId);
//                taskService.setVariable(taskId, "userName", userMap.get("userName"));
                    if(createUserId==null||"".equals(createUserId)){
                        logger.error("sendMsg createUserId is null");
                    }else{
                        Map<String,Object> queryPhoneMap = new HashMap<String, Object>();
                        queryPhoneMap.put("userId",createUserId);
                        AjaxJson phoneAjaxJson = new DbServiceRequestUtil().queryOperPhone(JacksonUitl.getObjectMapper().writeValueAsString(queryPhoneMap));
                        if(phoneAjaxJson.isSuccess()){
//                        sender = sender + "," + phoneAjaxJson.getMsg();
                            exeUserPhone = phoneAjaxJson.getMsg();
                            taskService.setVariable(taskId,"exeUserPhone",exeUserPhone);
                        }else{
                            logger.error("sendMsg createUser phone is not query");
                        }
                    }

                    script = sender + ("".equals(exeUserPhone)?"":(","+exeUserPhone));
//                    userMap.put("exeUserPhone",exeUserPhone);
                }

                logger.info("进入发短信参数处理方法：whiteListPasswordMap"+SystemCacheUtil.whiteListPasswordMap.get(processInstId));
                logger.info("进入发短信参数处理方法：whiteListPasswordMap"+ taskService.getVariable(taskId,"whiteListPassword"));
                sendMsg = this.opsSendMsg(sendMsg,taskService.getVariables(taskId),userMap);
                mapScriptParams.put("sender",sender + ("".equals(exeUserPhone)?"":(","+exeUserPhone)));
                mapScriptParams.put("sendMsg",sendMsg);
                String jsonParams = JacksonUitl.getObjectMapper().writeValueAsString(mapScriptParams);
                ajaxJson = new DbServiceRequestUtil().sendSms(jsonParams);
                taskService.setVariable(taskId,"returnCode",ajaxJson.getCode());
                taskService.setVariableLocal(taskId, "result", ajaxJson.getMsg());
                logger.error("配置了输出："+resultParmas);
                ajaxJson.setMsg(sendMsg);
                if(!ajaxJson.isSuccess()){
                    //将任务节点改为失败
                    FlowFormDb.updateFlowFormState(4,processInstId,taskDefinitionKey,ajaxJson.getCode(),ajaxJson.getMsg(),script);
                }else {
                    //将任务节点改为成功
                    FlowFormDb.updateFlowFormState(5,processInstId,taskDefinitionKey,ajaxJson.getCode(),ajaxJson.getMsg(),script);
                }
                if(resultParmas!=null&&!"".equals(resultParmas)){
                    taskService.setVariable(taskId,resultParmas,ajaxJson.getCode());
                    ajaxJson.setSuccess(true);

                }




            } catch (Exception e) {
                e.printStackTrace();
                ajaxJson.setSuccess(false) ;
                ajaxJson.setMsg(e.getMessage());
                ajaxJson.setCode("400");
                //将任务节点改为失败
                FlowFormDb.updateFlowFormState(4,processInstId,taskDefinitionKey,ajaxJson.getCode(),ajaxJson.getMsg(),script);
                taskService.setVariable(taskId, "returnCode", "10000");
                taskService.setVariableLocal(taskId, "result", e.getMessage());
//            formService.saveFormInstanceByFormModelId(completeTaskFormRepresentation.getValues(), completeTaskFormRepresentation.getFormId(), taskId, task.getProcessInstanceId());
            }


        if(ajaxJson.isSuccess() ){
            taskService.completeTaskWithForm(taskId, completeTaskFormRepresentation.getFormId(),
                    completeTaskFormRepresentation.getOutcome(), completeTaskFormRepresentation.getValues());
//            ProcessInstance pro= (ProcessInstance) taskService.createTaskQuery().processInstanceId(processInstId).singleResult();
            System.out.println("task count"+taskService.createTaskQuery().processInstanceId(processInstId).count());

            if(FlowFormDb.isEnd(processInstId)){
                System.out.println("=======判断是否执行完成====");

                //将流程状态置为运行成功
//                FlowDb.updateFlowState(5, processInstId);
            }
        }else{
            //将流程状态置为运行失败
//            FlowDb.updateFlowState(4, processInstId);
        }
        logger.error("==============sendSmsTask end=============");
        return  ajaxJson;
    }


    public Map<String,String> granteeNameMap(){
        Map<String,String> whiteListGranteeMap = new LinkedHashMap<>();
        whiteListGranteeMap.put("somdbdev","高权限");
        whiteListGranteeMap.put("somdbmod","中权限");
        whiteListGranteeMap.put("somdbqry","低权限");
        whiteListGranteeMap.put("appadm_super","超级权限");
        whiteListGranteeMap.put("appadm_high","高权限");
        whiteListGranteeMap.put("appadm_middle","中权限");
        whiteListGranteeMap.put("appadm_low","低权限");
        return whiteListGranteeMap;
    }

    /**
     * 处理模板参数
     * @param map
     * @return
     */
    public String opsSendMsg(String sendMsm,Map<String,Object> map,Map<String,String> userMap){



        String regEx = "\\{\\w*\\}";
        Pattern pat = Pattern.compile(regEx);
        Matcher mat = pat.matcher(sendMsm);
        String paramsName = "";
        int i=0;
        String name="";
        String value = "";
        String sendMsgReplace = sendMsm;
        while(mat.find()){
            name = mat.group().replace("{", "").replace("}", "").trim();
            //當前時間
            if("date".equals(name)){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = sdf.format(new Date());
                sendMsgReplace = sendMsgReplace.replaceAll("\\{"+name+"\\}",dateStr);
            }else if("granteeName".equals(name)){
                Map<String,String>  whiteListGranteeMap = granteeNameMap();
                logger.info("grantee======================="+map.get("grantee").toString());
                String granteeName = whiteListGranteeMap.get(map.get("grantee").toString())==null?"":whiteListGranteeMap.get(map.get("grantee").toString());
                sendMsgReplace = sendMsgReplace.replaceAll("\\{"+name+"\\}",granteeName);
            }else if("userId".equals(name)){
                sendMsgReplace = sendMsgReplace.replaceAll("\\{"+name+"\\}",userMap.get("userId"));
            }else if("userName".equals(name)){
                sendMsgReplace = sendMsgReplace.replaceAll("\\{"+name+"\\}",userMap.get("userName"));
            }else if("exeUserPhone".equals(name)){
                sendMsgReplace = sendMsgReplace.replaceAll("\\{"+name+"\\}",userMap.get("exeUserPhone")!=null?userMap.get("exeUserPhone").toString():"");
            }else{
//                Object vo = taskService.getVariable(taskId,name);
//                if(null == vo){
//                    value = vo.toString();
//                }else{
//                    value = map.get(name)!=null?map.get(name).toString():"";
//                }
                value = map.get(name)!=null?map.get(name).toString():"";
                sendMsgReplace = sendMsgReplace.replaceAll("\\{"+name+"\\}",value);
            }

//            if(StringUtils.isEmpty(value)){
//                params.add(null);
//            }
//            else{
//                params.add(value);
//            }
        }

        logger.info("sendMsm:"+paramsName);
//        sql= sql.replaceAll(regEx,"\\?");
        return sendMsgReplace;
    }

    public static void main(String [] args){
        String testMsg = "您好，数据库服务平台在{date}给{developer}白名单授权执行成功！";
        Map map = new LinkedHashMap();
        map.put("developer","teste");
//        System.out.println(new CusSendSmsTask().opsSendMsg(testMsg,map));
    }
}
